<?php
class Application_Model_ImageMapper
{
	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Image');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Image $image)
	{
		$data = array(
				'created' => $image->getcreated(),
				'url' => $image->getUrl(),
		);
	
		if (null === ($id = $image->getId())) {
			unset($data['id']);
			return $this->getDbTable()->insert($data);
		} else {
			return $this->getDbTable()->update($data, array('id = ?' => $id));
		}
	}
	
	public function find($id, Application_Model_Image $image)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$image->setId($row->id_image);
		$image->setCreated($row->created);
		$image->setUrl($row->url);
		return $image;
	}
	
	public function fetchAll()
	{
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_Address();
			$entry->setId($row->id)
			->setCreated($row->created)
			->setUrl($row->url);
			$entries[] = $entry;
		}
		return $entries;
	}
	
	public function delete($id)
	{
		$result = $this->getDbTable()->find($id);
		if (0 != count($result)) {
			$this->getDbTable()->delete(array('id_image = ?' => $id));
		}
	
	}
}